<?php
/**
 * api controller class
 *
 * @author raphael seebacher <raphasee@ee.ethz.ch>
 * @version 0.01
 */
class api_controller extends front_controller {
    protected $request = NULL;
    protected $message = NULL;
    protected $response = NULL;
    protected $view = NULL;

    public static function is_valid_request_url($request) {
        return ($request->get_request_string() == config::get('api_identifier'));
    }

    protected function set_message_from_request() {
        if ($msg_raw = $this->request->get_property('message')) {
            $this->message = json_decode($msg_raw, true);
        }
        else {
            throw new no_message_exception();
        }
    }

    protected function add_to_response($element_response) {
        if (is_array($this->response)) {
            $this->response = array_merge($this->response, $element_response);
        }
        else {
            $this->response = $element_response;
        }
    }

    protected function send_response() {
        $this->view->send_header();
        echo $this->view->get_content();
    }

    protected function process_message() {
        $message_elements_enabled_array =
            explode(' ', trim(config::get('message_elements_enabled')));

        foreach ($message_elements_enabled_array as $message_element_name) {
            try {
                $message_element = new $message_element_name($this->message);
                $message_element_response = $message_element->get_response();
                $this->add_to_response($message_element_response);

                $this->view = new json_view();
                $this->view->set_content($this->response);
            }
            catch (no_element_exception $e) {
                $required =
                    (config::get($message_element_name, 'required'));

                if ($required) {
                    $this->view = new error_view($e->getMessage(), 400);
                }
            }
            catch (Exception $e) {
                $this->view = new error_view(
                  'Check your config file. Not all configured message elements '
                  .'have been found.',
                  500
                );
            }
        }
    }

    public function process_request() {
        try {
            $this->set_message_from_request();
            $this->process_message();
        }
        catch (no_message_exception $e) {
            $error_view = new error_view($e->getMessage(), 400);
        }

        $this->send_response();
    }
}
?>